package com.e2oto.seller.modules.launch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.e2oto.seller.common.base.BaseMvpActivity;
import com.e2oto.seller.common.download.DownLoadManager;
import com.e2oto.seller.common.utils.LogTools;
import com.e2oto.seller.common.utils.RegexTools;
import com.e2oto.seller.common.utils.SPtools;
import com.e2oto.seller.common.utils.ToastUtils;
import com.e2oto.seller.modules.SellerApp;
import com.e2oto.seller.modules.launch.bean.CodeBean;
import com.e2oto.seller.modules.launch.bean.LoginBean;
import com.e2oto.seller.modules.launch.presenter.LoginPresenter;
import com.e2oto.seller.modules.launch.views.LoginView;
import com.e2oto.seller.R;
import com.e2oto.seller.modules.seller.bean.RxBusBean;
import com.e2oto.seller.modules.seller.ui.HomeActivity;
import com.e2oto.seller.modules.seller.ui.ShopAptitudeActivity;
import com.e2oto.seller.modules.seller.ui.ShopBaseInfoActivity;
import com.e2oto.seller.widget.LoginEditText;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class LoginActivity extends BaseMvpActivity<LoginView, LoginPresenter> implements LoginView {

    @BindView(R.id.login_tab)
    TabLayout tabLayout;
    @BindView(R.id.login_et)
    LoginEditText loginEditText;
    @BindView(R.id.password_et)
    LoginEditText passwordEditText;
    @BindView(R.id.input_phone_et)
    LoginEditText inputPhoneEditText;
    @BindView(R.id.login_code_et)
    EditText codeEditText;
    @BindView(R.id.login_quick_login_region)
    LinearLayout quickLoginRegion;
    @BindView(R.id.login_normal_region)
    LinearLayout normalLoginRegion;
    @BindView(R.id.login_get_code)
    TextView sendCodeTv;

    private CodeBean codeBean;

    @Override
    protected void afterView(Bundle savedInstanceState) {
        super.afterView(savedInstanceState);
        tabLayout.addTab(tabLayout.newTab().setText("常规登录"));
        tabLayout.addTab(tabLayout.newTab().setText("快捷登录"));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    normalLoginRegion.setVisibility(View.VISIBLE);
                    quickLoginRegion.setVisibility(View.GONE);
                } else {
                    normalLoginRegion.setVisibility(View.GONE);
                    quickLoginRegion.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loginEditText.getEditText().setText("15583566886");
        passwordEditText.getEditText().setText("123456");
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void onReceiveRxMessage(RxBusBean anyType) {
        super.onReceiveRxMessage(anyType);
        switch (anyType.getType()) {
            case DownLoadManager.DOWNLOAD_ING:
                LogTools.e(anyType.getMsg());
                break;
            case DownLoadManager.DOWNLOAD_SUCCESS:
                LogTools.e("BUS_SUCCESS");
                break;
            case DownLoadManager.DOWNLOAD_START:
                LogTools.e("BUS_START");
                break;
            case DownLoadManager.DOWNLOAD_ERROR:
                LogTools.e("BUS_ERROR:" + anyType.getMsg());
                break;
        }
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @OnClick({R.id.login_login_btn, R.id.login_get_code, R.id.login_register, R.id.login_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_login_btn:
                if (tabLayout.getSelectedTabPosition() == 0) {//常规登录
                    String phone = loginEditText.getEditText().getText().toString().trim();
                    String password = passwordEditText.getEditText().getText().toString().trim();
                    if (!RegexTools.isMobileSimple(phone)) {
                        showMessage("请输入正确的手机号码");
                        return;
                    }
                    if (TextUtils.isEmpty(password)) {
                        showMessage("密码不能为空");
                        return;
                    }
                    if (password.length() < 6) {
                        showMessage("密码不能小于6位数");
                        return;
                    }
                    mPresenter.login(phone, password);
                } else {//快捷登录
                    String phone = inputPhoneEditText.getEditText().getText().toString().trim();
                    String code = codeEditText.getText().toString().trim();
                    if (!RegexTools.isMobileSimple(phone)) {
                        showMessage("请输入正确的手机号码");
                        return;
                    }
                    if (TextUtils.isEmpty(code)) {
                        showMessage("请输入验证码");
                        return;
                    }
                    if (code.length() != 4) {
                        showMessage("请输入4位数字的验证码");
                        return;
                    }
                    mPresenter.quickLogin(phone, code);
                }
                break;
            case R.id.login_get_code:
                String phone = inputPhoneEditText.getEditText().getText().toString().trim();
                if (!RegexTools.isMobileSimple(phone)) {
                    showMessage("请输入正确的手机号码");
                    return;
                }
                mPresenter.sendCode(phone);
                break;
            case R.id.login_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.login_forget:
                startActivity(new Intent(this, ForgetActivity.class));
                break;
        }

    }

    @Override
    public void showMessage(String msg) {
        ToastUtils.INSTANCE.showToast(this, msg);
    }

    @Override
    public void loginResult(LoginBean loginBean) {
        SellerApp.userId = loginBean.getUser_id() + "";
        SellerApp.sellerId = loginBean.getSeller_id() + "";
        SPtools.put(this, "category_id", loginBean.getCategory_id());
        SPtools.put(this, "batch_category_id", loginBean.getBatch_category_id());

        if (loginBean.getSeller_status() == 0) {
            startActivity(new Intent(this, ShopBaseInfoActivity.class));
        } else if (loginBean.getSeller_status() == 1) {
            ToastUtils.INSTANCE.showToast(this, "您提交的入驻申请正在审核中");
            startActivity(new Intent(this, HomeActivity.class));
        } else {
            startActivity(new Intent(this, HomeActivity.class));
        }
        exitApp();

    }

    @Override
    public void sendCodeResult(CodeBean codeBean) {
        this.codeBean = codeBean;
        LogTools.e("验证码是：" + codeBean.getCode());
        final int count = 60;
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return count - aLong;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        sendCodeTv.setTextColor(ContextCompat.getColor(LoginActivity.this, R.color.theme_color));
                        sendCodeTv.setClickable(false);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        sendCodeTv.setText("验证码已发送" + aLong);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        sendCodeTv.setTextColor(ContextCompat.getColor(LoginActivity.this, R.color.black));
                        sendCodeTv.setClickable(true);
                        sendCodeTv.setText("获取验证码");
                    }
                });
    }


}
